/*
 * @Description: 医嘱列表Mock，提供完整CRUD接口与常用业务操作
 * 说明：仅用于前端联调与演示，真实项目请替换为后端API
 */

// 内存数据库：示例数据
let _autoId = 10000
let _orders = [
  {
    id: 1,
    bedNo: '01A',
    patientName: '张三苏',
    startTime: '2025-11-17 08:00:00',
    orderType: 'drug',
    orderTypeLabel: '药品医嘱',
    treatmentType: '门诊',
    status: 'verify', // verify|execute|canceled
    statusLabel: '待核对',
    remark: '口服，饭后',
    doctorName: '李医生',
    stopDoctorName: '',
    stopTime: ''
  },
  {
    id: 2,
    bedNo: '01B',
    patientName: '李四奇',
    startTime: '2025-11-17 09:00:00',
    orderType: 'lab',
    orderTypeLabel: '检验医嘱',
    treatmentType: '住院',
    status: 'execute',
    statusLabel: '已执行',
    remark: '血常规',
    doctorName: '王医生',
    stopDoctorName: '',
    stopTime: ''
  },
  {
    id: 3,
    bedNo: '02A',
    patientName: '王五谷',
    startTime: '2025-11-16 10:30:00',
    orderType: 'treat',
    orderTypeLabel: '治疗医嘱',
    treatmentType: '住院',
    status: 'canceled',
    statusLabel: '已撤销',
    remark: '停止输液',
    doctorName: '赵医生',
    stopDoctorName: '赵医生',
    stopTime: '2025-11-17 11:00:00'
  }
]

// 统一返回体封装
const ok = (data, message = 'success') => ({ code: 200, data, message })
const err = (message = 'error', code = 400) => ({ code, message })

// 列表查询（支持状态与简单过滤、分页）
export const getOrderList = ({ status = 'all', pageNum = 1, pageSize = 10, filters = {} } = {}) => {
  // 过滤状态
  let list = _orders.slice()
  if (status !== 'all') {
    list = list.filter(item => item.status === status)
  }

  // 简单过滤：床位、患者、医嘱类型、诊疗类型、时间区间
  if (filters) {
    const { bedNo, patientName, orderType, treatmentType, startTime, endTime, orderContent } = filters
    if (bedNo) list = list.filter(i => String(i.bedNo).includes(String(bedNo)))
    if (patientName) list = list.filter(i => String(i.patientName).includes(String(patientName)))
    if (orderType) list = list.filter(i => String(i.orderType) === String(orderType))
    if (treatmentType) list = list.filter(i => String(i.treatmentType) === String(treatmentType))
    if (orderContent) list = list.filter(i => String(i.remark).includes(String(orderContent)))
    if (startTime) list = list.filter(i => new Date(i.startTime) >= new Date(startTime))
    if (endTime) list = list.filter(i => i.stopTime && new Date(i.stopTime) <= new Date(endTime))
  }

  const total = list.length
  const start = (pageNum - 1) * pageSize
  const end = start + pageSize
  return ok({ list: list.slice(start, end), total })
}

// 创建
export const createOrder = payload => {
  const id = ++_autoId
  const record = {
    id,
    bedNo: payload.bedNo || '',
    patientName: payload.patientName || '',
    startTime: payload.startTime || new Date().toISOString().slice(0, 19).replace('T', ' '),
    orderType: payload.orderType || 'other',
    orderTypeLabel: payload.orderTypeLabel || '其他医嘱',
    treatmentType: payload.treatmentType || '住院',
    status: payload.status || 'verify',
    statusLabel: payload.statusLabel || '待核对',
    remark: payload.remark || '',
    doctorName: payload.doctorName || '',
    stopDoctorName: '',
    stopTime: ''
  }
  _orders.unshift(record)
  return ok(record, 'created')
}

// 更新
export const updateOrder = (id, payload) => {
  const idx = _orders.findIndex(i => i.id === Number(id))
  if (idx === -1) return err('not found', 404)
  _orders[idx] = { ..._orders[idx], ...payload }
  return ok(_orders[idx], 'updated')
}

// 删除
export const deleteOrder = id => {
  const before = _orders.length
  _orders = _orders.filter(i => i.id !== Number(id))
  if (_orders.length === before) return err('not found', 404)
  return ok(null, 'deleted')
}

// 批量删除
export const deleteOrders = ids => {
  _orders = _orders.filter(i => !ids.includes(i.id))
  return ok({ deleted: ids }, 'deleted')
}

// 业务：核对
export const checkOrders = ids => {
  _orders.forEach(i => {
    if (ids.includes(i.id)) {
      i.status = 'verify'
      i.statusLabel = '待核对'
    }
  })
  return ok({ ids }, 'checked')
}

// 业务：执行
export const executeOrders = ids => {
  _orders.forEach(i => {
    if (ids.includes(i.id)) {
      i.status = 'execute'
      i.statusLabel = '已执行'
    }
  })
  return ok({ ids }, 'executed')
}

// 业务：撤销（停止/撤销）
export const cancelOrders = ids => {
  const now = new Date().toISOString().slice(0, 19).replace('T', ' ')
  _orders.forEach(i => {
    if (ids.includes(i.id)) {
      i.status = 'canceled'
      i.statusLabel = '已撤销'
      i.stopDoctorName = i.doctorName
      i.stopTime = now
    }
  })
  return ok({ ids }, 'canceled')
}

export default {
  getOrderList,
  createOrder,
  updateOrder,
  deleteOrder,
  deleteOrders,
  checkOrders,
  executeOrders,
  cancelOrders
}
